<template>
  <div>
    <el-image
      v-if="imgUrl"
      :src="imgUrl"
      :style="{ width: width, maxHeight: height }"
    >
    </el-image>
    <el-upload
      v-else
      :action="baseUrl + actionUrl"
      list-type="picture-card"
      :show-file-list="false"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :headers="headers"
      class="pic-single"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <i
      class="el-icon-circle-close"
      style="float: right; font-size: 24px; cursor: pointer; margin-right: 35px"
      v-if="imgUrl"
      @click="handleRemove"
    ></i>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      append-to-body
      width="800px"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
let baseUrl = process.env.VUE_APP_BASE_API;
import { getToken } from "@/utils/auth";

export default {
  name: "uploadImg",
  props: {
    actionUrl: {
      type: String,
    },
    imgUrl: {
      type: String,
    },
    width: {
      type: String,
      default: "178px",
    },
    height: {
      type: String,
      default: "178px",
    },
    size: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      baseUrl: baseUrl,
      dialogImageUrl: "",
      dialogVisible: false,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  methods: {
    handleSuccess(res, file) {
      this.$emit("update:imgUrl", res.data.url);
    },
    beforeUpload(file) {
      const isIMG = file.type == "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < this.size;

      if (!isIMG) {
        this.$message.error("上传图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过 ${this.size}MB!`);
      }
      return isIMG && isLt2M;
    },
    handleRemove() {
      this.$emit("update:imgUrl", "");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss">
</style>
